package com.ghp.interfas.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ghp
 * @title 流量染色拦截器
 * @description
 */
@Slf4j
public class DyeDataInterceptor implements HandlerInterceptor {
    /**
     * 请求染色头
     */
    private static final String DYE_DATA_HEADER = "X-Dye-Data";
    /**
     * 染色数据
     */
    private static final String DYE_DATA_VALUE = "ghp";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的染色数据
        String dyeData = request.getHeader(DYE_DATA_HEADER);
        if (dyeData == null || !dyeData.equals(DYE_DATA_VALUE)) {
            log.warn("非法访问");
            // 如果染色数据不存在或者不匹配，则返回错误响应
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        // 继续向下执行
        return true;
    }
}
